<script setup lang="ts">
  import { HMessage, HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import {
    useInspectCustomFieldForm,
    useGetInspectCustomFieldDetail,
    useGetOptions,
  } from '@/services/pages/return-factory'
  import { ElDivider, FormInstance } from 'element-plus'
  import { h, ref, watch } from 'vue'
  import { ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElSwitch, ElSpace } from 'element-plus'
  import _ from 'lodash'

  const { loading: saveFormLodaing, form, submit, resetForm } = useInspectCustomFieldForm()
  const {
    fieldDetail,
    loading: getFieldDetailLoading,
    getDetail,
  } = useGetInspectCustomFieldDetail()
  const {
    options: returnFactoryModuleOptions,
    getOptionsParam,
    getOptionsLoading,
    getOptions,
  } = useGetOptions()

  defineOptions({
    name: 'InspectCustomFieldModalReturnFactory',
  })

  const props = defineProps({
    fieldId: {
      type: String,
      default: () => '',
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  const visible = defineModel('visible', { type: Boolean, default: false })
  const fieldTypeOptions = ref([
    {
      label: '文本',
      value: 1,
    },
    {
      label: '多行文本',
      value: 2,
    },
    {
      label: '单选',
      value: 3,
    },
    {
      label: '多选',
      value: 4,
    },
    {
      label: '多图',
      value: 5,
    },
    {
      label: '附件',
      value: 6,
    },
    {
      label: '视频',
      value: 7,
    },
    {
      label: '评分',
      value: 8,
    },
  ])
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })
  const rules = ref({
    name: [{ required: true, message: '请输入字段名称', trigger: ['blur', 'change'] }],
    type: [{ required: true, message: '请选择字段类型', trigger: ['blur', 'change'] }],
    status: [{ required: true, message: '请选择字段状态', trigger: ['blur', 'change'] }],
    required: [{ required: true, message: '请选择是否必填', trigger: ['blur', 'change'] }],
    fieldContent: [{ required: true, message: '请输入字段内容', trigger: ['blur', 'change'] }],
  })
  const formInstance = ref<FormInstance | null>(null)

  // 返厂模块id选择列表
  const returnFactoryModuleSelectedIds = ref<Array<string>>([])

  const hideDrawer = () => {
    resetForm()
    visible.value = false
  }

  const handleChangeFieldType = () => {
    if ([3, 4].includes(form.value.type) && form.value.fieldContentVos.length === 0) {
      addSelectOption()
    }
  }

  const addSelectOption = () => {
    form.value.fieldContentVos.push({
      id: '',
      val: '',
    })
  }

  const handleDelSelectOption = (index: number) => {
    const fieldContent = form.value.fieldContentVos[index]
    if (fieldContent) {
      if (fieldContent.id) {
        form.value.delFieldContentIds.push(fieldContent.id)
      }
      form.value.fieldContentVos.splice(index, 1)
    }
  }

  const handleSizeInput = () => {
    form.value.uploadSize = Number(String(form.value.uploadSize).replace(/[^\d]/g, ''))
    if (form.value.uploadSize > 100) {
      form.value.uploadSize = 100
    }

    if (form.value.uploadSize < 1) {
      form.value.uploadSize = 1
    }
  }

  const handleQtyInput = () => {
    form.value.uploadQty = Number(String(form.value.uploadQty).replace(/[^\d]/g, ''))
    if (form.value.uploadQty > 10) {
      form.value.uploadQty = 10
    }

    if (form.value.uploadQty < 1) {
      form.value.uploadQty = 1
    }
  }

  const onSubmit = async () => {
    if (formInstance.value) {
      await formInstance.value.validate()
      const res = await submit()
      if (res.code === 20000) {
        HMessage.success(infoTip.returnFactory.inspectCustomField.formSaveSuccess)
        hideDrawer()
        emits('update')
        return
      }
      HMessageBox.error(infoTip.returnFactory.inspectCustomField.errCode[res.code] || res.message)
    }
  }

  /**
   * 返厂模块筛选事件
   */
  const handleGetReturnFactoryModule = _.debounce((keyword: string) => {
    if (getOptionsParam.value.name !== keyword) {
      getOptionsParam.value.name = keyword
      getOptions()
    }
  }, 600)

  /**
   * 返厂模块选择事件
   * @param {Array<string>} ids - 模块id集合
   */
  const handleReturnModuleSelect = (ids: Array<string>) => {
    returnFactoryModuleSelectedIds.value = ids
    ids.forEach((id) => {
      const { repairModuleFieldRelationVos } = form.value
      if (!repairModuleFieldRelationVos.map((item) => item.repairModuleId).includes(id)) {
        form.value.repairModuleFieldRelationVos.push({
          id: '',
          mobileShow: true,
          required: false,
          repairModuleId: id,
          repairFieldId: form.value.id,
        })
      }
    })
  }

  /**
   * 返厂模块移除事件
   * @param {String} id - 模块id
   */
  const handleReturnModuleRemove = (id: string) => {
    const module = form.value.repairModuleFieldRelationVos.find((item) => {
      return item.repairModuleId === id
    })
    if (module) {
      form.value.repairModuleFieldRelationVos = form.value.repairModuleFieldRelationVos.filter(
        (item) => item.repairModuleId !== id,
      )
      form.value.delRepairModuleFieldRelationIds.push(module.id)
    }
  }

  watch(
    visible,
    async (value) => {
      if (value) {
        getOptions()
        if (props.fieldId) {
          await getDetail(props.fieldId)
          returnFactoryModuleSelectedIds.value = fieldDetail.value.repairModuleFieldRelationVos.map(
            (item) => item.repairModuleId,
          )
          form.value = {
            delFieldContentIds: [],
            fieldContentVos: fieldDetail.value.fieldContentVos,
            id: fieldDetail.value.id,
            mobileShow: fieldDetail.value.mobileShow,
            name: fieldDetail.value.name,
            required: fieldDetail.value.required,
            status: fieldDetail.value.status,
            tip: fieldDetail.value.tip,
            type: fieldDetail.value.type,
            uploadQty: fieldDetail.value.uploadQty,
            uploadSize: fieldDetail.value.uploadSize,
            delRepairModuleFieldRelationIds: [],
            repairModuleFieldRelationVos: fieldDetail.value.repairModuleFieldRelationVos.map(
              (item) => {
                return {
                  id: item.id,
                  repairModuleId: item.repairModuleId,
                  mobileShow: true,
                  required: false,
                  repairFieldId: fieldDetail.value.id,
                }
              },
            ),
          }
        }
      }
    },
    { immediate: true },
  )
</script>

<template>
  <h-drawer
    v-model="visible"
    :title="props.fieldId ? '编辑字段' : '添加字段'"
    :width="800"
    unit="px"
    :loading="saveFormLodaing || getFieldDetailLoading"
    @close="hideDrawer"
  >
    <el-form
      ref="formInstance"
      class="modal_form_content"
      inline-message
      label-position="top"
      :model="form"
      :rules="rules"
    >
      <!-- 字段名称 -->
      <el-form-item label="字段名称" prop="name">
        <el-input v-model.trim="form.name" placeholder="请输入字段名称" maxlength="10" />
      </el-form-item>

      <!-- 关联返厂模块 -->
      <el-form-item label="关联返厂模块" prop="repairModuleFieldRelationVos">
        <el-select
          v-model="returnFactoryModuleSelectedIds"
          filterable
          placeholder="请选择返厂模块"
          multiple
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="3"
          :loading="getOptionsLoading"
          :filter-method="handleGetReturnFactoryModule"
          @change="handleReturnModuleSelect"
          @remove-tag="handleReturnModuleRemove"
        >
          <el-option
            v-for="(option, optionIndex) in returnFactoryModuleOptions"
            :key="optionIndex"
            :label="option.name"
            :value="option.id"
            :disabled="option.disabled"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 字段类型 -->
      <el-form-item label="字段类型" prop="type">
        <el-select v-model="form.type" :disabled="!!props.fieldId" @change="handleChangeFieldType">
          <el-option
            v-for="(fieldType, fieldTypeIndex) in fieldTypeOptions"
            :key="fieldTypeIndex"
            :label="fieldType.label"
            :value="fieldType.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 提示信息 -->
      <el-form-item label="提示信息" prop="tip">
        <el-input v-model.trim="form.tip" placeholder="请输入提示信息" maxlength="20" />
      </el-form-item>

      <div class="same_line">
        <!-- 字段状态 -->
        <el-form-item label="字段状态" class="swtich-container-size-small" prop="status">
          <el-switch
            :model-value="!form.status"
            size="small"
            @change="form.status = !form.status"
          ></el-switch>
          <div class="text">{{ form.status ? '隐藏' : '显示' }}</div>
        </el-form-item>

        <!-- 是否必填 -->
        <el-form-item label="是否必填" prop="required" class="swtich-container-size-small">
          <el-switch v-model="form.required" size="small"></el-switch>
          <div class="text">{{ form.required ? '是' : '否' }}</div>
        </el-form-item>

        <!-- 移动端显示 -->
        <el-form-item label="移动端显示" class="swtich-container-size-small" prop="mobileShow">
          <el-switch v-model="form.mobileShow" size="small"></el-switch>
          <div class="text">{{ form.mobileShow ? '显示' : '隐藏' }}</div>
        </el-form-item>
      </div>

      <div v-if="[3, 4].includes(form.type)" class="select-options-wrapper">
        <!-- 多选/单选选项 -->
        <el-form-item
          v-for="(select, selectIndex) in form.fieldContentVos"
          :key="selectIndex"
          :label="`字段内容${selectIndex + 1}`"
          :prop="`fieldContentVos[${selectIndex}].val`"
          :rules="rules['name']"
        >
          <div class="select-option-content-wrapper">
            <el-input
              v-model.trim="form.fieldContentVos[selectIndex].val"
              placeholder="请输入字段内容"
              maxlength="15"
            />

            <div class="btn-group">
              <el-space :size="0" :spacer="spacer">
                <h-link
                  v-if="form.fieldContentVos.length > 1"
                  type="error"
                  @click="handleDelSelectOption(selectIndex)"
                  >删除</h-link
                >
                <h-link v-if="selectIndex === 0" @click="addSelectOption">添加</h-link>
              </el-space>
            </div>
          </div>
        </el-form-item>
      </div>

      <template v-if="[5, 6, 7].includes(form.type)">
        <!-- 最大尺寸(MB) -->
        <el-form-item label="最大尺寸(MB)" prop="uploadSize">
          <el-input
            v-model.trim="form.uploadSize"
            plceholder="请输入最大尺寸"
            @input="handleSizeInput"
          />
        </el-form-item>

        <!-- 上传数量 -->
        <el-form-item label="上传数量" prop="uploadQty">
          <el-input
            v-model.trim="form.uploadQty"
            plceholder="请输入上传数量"
            @input="handleQtyInput"
          />
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <h-button is-modal type="primary" @click="onSubmit">确定</h-button>
      <h-button is-modal @click="hideDrawer">取消</h-button>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  .select-options-wrapper {
    height: 480px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    row-gap: 12px;

    .select-option-content-wrapper {
      width: 100%;
      display: flex;
      column-gap: 12px;
      height: 28px;

      :deep(.el-input) {
        width: 430px;
      }

      .btn-group {
        height: 28px;
        display: flex;
        align-items: center;
      }
    }
  }
</style>
